﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using System.Xml.Serialization;
using System;

namespace MessageHandler
{
	class Persistence
	{
		private string fileName = "users.data";

		internal Dictionary<string, UserInfo> Load()
		{
			List<UserInfo> userInfos = new List<UserInfo>();
			Dictionary<string, UserInfo> users = new Dictionary<string, UserInfo>();
			if (File.Exists(fileName))
			{
				userInfos = (from u in XDocument.Load(fileName).Root.Elements("UserInfo")
							 select new UserInfo
							 {
								 ip = (string)u.Element("ip"),
								 password = (string)u.Element("password"),
								 port = (int)u.Element("port"),
								 username = (string)u.Element("username"),
								 firstname = (string)u.Element("firstname"),
								 lastname = (string)u.Element("lastname"),
								 birthday = u.Element("birthday") != null ? (DateTime)u.Element("birthday") : DateTime.Now,
								 gender = u.Element("gender") != null ? (bool)u.Element("gender") : false,
								 genderSpecified = true,
								 contacts = (from c in u.Elements("contacts")
											 select (string)c.Value).ToArray()
							 }).ToList();
			}
			foreach (UserInfo user in userInfos)
			{
				if (!user.birthday.Date.Equals(DateTime.Now.Date))
				{
					user.birthdaySpecified = true;
				}
				users.Add(user.username, user);
			}

			return users;
		}

		internal void Persist(Dictionary<string, UserInfo> userInfos)
		{
			if (userInfos.Count > 0)
			{
				List<UserInfo> users = new List<UserInfo>(userInfos.Values);
				XmlSerializer x = new XmlSerializer(typeof(List<UserInfo>));
				StreamWriter writer = new StreamWriter(fileName, false);
				x.Serialize(writer, users);
				writer.Close();
			}
		}

	}
}
